package com.anonymous.community;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;

import com.anonymous.community.api.ApiClient;
import com.anonymous.community.api.ApiService;
import com.anonymous.community.api.model.CommentTreeResponse;
import com.anonymous.community.api.model.CreateCommentRequest;
import com.anonymous.community.api.model.CreateCommentResponse;
import com.anonymous.community.api.model.GenericResponse;
import com.anonymous.community.api.model.LikeResponse;
import com.anonymous.community.api.model.PostDetailResponse;
import com.anonymous.community.api.model.ReportRequest;
import com.anonymous.community.databinding.ActivityPostDetailBinding;
import com.anonymous.community.ui.base.BaseActivity;
import com.anonymous.community.ui.home.CommentAdapter;
import com.anonymous.community.utils.TokenManager;
import com.tencent.bugly.crashreport.CrashReport;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 帖子详情Activity
 * 显示帖子完整内容和评论列表
 */
public class PostDetailActivity extends BaseActivity implements CommentAdapter.OnCommentInteractionListener {

    private ActivityPostDetailBinding binding;
    private ApiService apiService;
    private CommentAdapter commentAdapter;
    private int postId;
    private PostDetailResponse.PostInfo currentPost;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityPostDetailBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        // 获取传入的帖子ID
        postId = getIntent().getIntExtra("post_id", 0);
        if (postId == 0) {
            Toast.makeText(this, "帖子不存在", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        apiService = ApiClient.getApiService();

        setupViews();
        loadPostDetail();
        loadComments();
    }

    private void setupViews() {
        // 返回按钮
        binding.btnBack.setOnClickListener(v -> finish());

        // 评论列表
        commentAdapter = new CommentAdapter();
        commentAdapter.setOnCommentInteractionListener(this);
        binding.rvComments.setLayoutManager(new LinearLayoutManager(this));
        binding.rvComments.setAdapter(commentAdapter);

        // 发送评论按钮
        binding.btnSendComment.setOnClickListener(v -> sendComment());

        // 点赞按钮
        binding.layoutLike.setOnClickListener(v -> toggleLike());

        // 举报按钮
        binding.btnReport.setOnClickListener(v -> showReportDialog());

        // 下拉刷新
        binding.swipeRefresh.setOnRefreshListener(() -> {
            loadPostDetail();
            loadComments();
        });
        binding.swipeRefresh.setColorSchemeColors(getResources().getColor(R.color.black));
    }

    /**
     * 加载帖子详情
     */
    private void loadPostDetail() {
        apiService.getPostDetail(postId)
                .enqueue(new Callback<PostDetailResponse>() {
                    @Override
                    public void onResponse(Call<PostDetailResponse> call, Response<PostDetailResponse> response) {
                        binding.swipeRefresh.setRefreshing(false);
                        
                        if (response.isSuccessful() && response.body() != null) {
                            currentPost = response.body().getPost();
                            displayPost(currentPost);
                        } else {
                            Toast.makeText(PostDetailActivity.this, "加载失败", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<PostDetailResponse> call, Throwable t) {
                        binding.swipeRefresh.setRefreshing(false);
                        Toast.makeText(PostDetailActivity.this, "网络连接失败", Toast.LENGTH_SHORT).show();
                    }
                });
    }

    /**
     * 显示帖子信息
     */
    private void displayPost(PostDetailResponse.PostInfo post) {
        // 用户信息
        binding.tvUsername.setText(post.getAnonymousId());
        binding.tvPostTime.setText(formatTime(post.getCreatedAt()));

        // 帖子内容
        binding.tvContent.setText(post.getContent());

        // 互动数据
        binding.tvLikeCount.setText(String.valueOf(post.getLikeCount()));
        binding.tvCommentCount.setText(String.valueOf(post.getCommentCount()));
        binding.tvViewCount.setText(String.valueOf(post.getViewCount()));

        // 点赞状态
        updateLikeStatus(post.isLiked(), post.getLikeCount());
    }

    /**
     * 加载评论列表
     */
    private void loadComments() {
        apiService.getCommentTree(postId, 3, "latest")
                .enqueue(new Callback<CommentTreeResponse>() {
                    @Override
                    public void onResponse(Call<CommentTreeResponse> call, Response<CommentTreeResponse> response) {
                        binding.swipeRefresh.setRefreshing(false);
                        
                        if (response.isSuccessful() && response.body() != null) {
                            CommentTreeResponse treeResponse = response.body();
                            if (treeResponse.getComments() != null && !treeResponse.getComments().isEmpty()) {
                                commentAdapter.setComments(treeResponse.getComments());
                                binding.tvEmptyComment.setVisibility(View.GONE);
                            } else {
                                commentAdapter.clearComments();
                                binding.tvEmptyComment.setVisibility(View.VISIBLE);
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<CommentTreeResponse> call, Throwable t) {
                        binding.swipeRefresh.setRefreshing(false);
                        Toast.makeText(PostDetailActivity.this, "加载评论失败", Toast.LENGTH_SHORT).show();
                    }
                });
    }

    /**
     * 发送评论
     */
    private void sendComment() {
        String content = binding.etComment.getText().toString().trim();
        
        if (content.isEmpty()) {
            Toast.makeText(this, "请输入评论内容", Toast.LENGTH_SHORT).show();
            return;
        }

        if (content.length() > 1000) {
            Toast.makeText(this, "评论内容不能超过1000字", Toast.LENGTH_SHORT).show();
            return;
        }

        String token = TokenManager.getToken(this);
        if (token == null || token.isEmpty()) {
            Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show();
            return;
        }

        binding.btnSendComment.setEnabled(false);

        CreateCommentRequest request = new CreateCommentRequest(content, null);
        apiService.createComment(token, postId, request)
                .enqueue(new Callback<CreateCommentResponse>() {
                    @Override
                    public void onResponse(Call<CreateCommentResponse> call, Response<CreateCommentResponse> response) {
                        binding.btnSendComment.setEnabled(true);
                        
                        if (response.isSuccessful() && response.body() != null) {
                            binding.etComment.setText("");
                            Toast.makeText(PostDetailActivity.this, "评论成功", Toast.LENGTH_SHORT).show();
                            
                            CrashReport.postCatchedException(new Exception("Event: Comment Success"));
                            
                            // 刷新评论列表
                            loadComments();
                            loadPostDetail(); // 更新评论数
                        } else {
                            String errorMsg = extractErrorMessage(response);
                            Toast.makeText(PostDetailActivity.this, 
                                TextUtils.isEmpty(errorMsg) ? "评论失败" : errorMsg, 
                                Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<CreateCommentResponse> call, Throwable t) {
                        binding.btnSendComment.setEnabled(true);
                        Toast.makeText(PostDetailActivity.this, "网络连接失败", Toast.LENGTH_SHORT).show();
                    }
                });
    }

    /**
     * 切换点赞状态
     */
    private void toggleLike() {
        String token = TokenManager.getToken(this);
        if (token == null || token.isEmpty()) {
            Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show();
            return;
        }

        apiService.toggleLike(token, "post", postId)
                .enqueue(new Callback<LikeResponse>() {
                    @Override
                    public void onResponse(Call<LikeResponse> call, Response<LikeResponse> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            LikeResponse likeResponse = response.body();
                            updateLikeStatus(likeResponse.isLiked(), likeResponse.getLikeCount());
                            
                            String message = likeResponse.isLiked() ? "已点赞" : "已取消点赞";
                            Toast.makeText(PostDetailActivity.this, message, Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<LikeResponse> call, Throwable t) {
                        Toast.makeText(PostDetailActivity.this, "操作失败", Toast.LENGTH_SHORT).show();
                    }
                });
    }

    /**
     * 更新点赞状态UI
     */
    private void updateLikeStatus(boolean liked, int count) {
        if (liked) {
            binding.ivLike.setImageResource(R.drawable.ic_like_filled);
            binding.ivLike.setColorFilter(getResources().getColor(R.color.black));
        } else {
            binding.ivLike.setImageResource(R.drawable.ic_like_outline);
            binding.ivLike.setColorFilter(getResources().getColor(R.color.colorGray));
        }
        binding.tvLikeCount.setText(String.valueOf(count));
    }

    /**
     * 显示举报对话框
     */
    private void showReportDialog() {
        String token = TokenManager.getToken(this);
        if (token == null || token.isEmpty()) {
            Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show();
            return;
        }

        android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(this);
        View dialogView = getLayoutInflater().inflate(R.layout.dialog_report, null);
        
        com.google.android.material.textfield.TextInputEditText etReason = dialogView.findViewById(R.id.et_reason);
        com.google.android.material.textfield.TextInputEditText etDescription = dialogView.findViewById(R.id.et_description);
        
        builder.setView(dialogView)
            .setTitle("举报帖子")
            .setPositiveButton("提交", (dialog, which) -> {
                String reason = etReason.getText().toString().trim();
                String description = etDescription.getText().toString().trim();
                
                if (reason.isEmpty()) {
                    Toast.makeText(this, "请输入举报原因", Toast.LENGTH_SHORT).show();
                    return;
                }
                
                submitReport(reason, description);
            })
            .setNegativeButton("取消", null)
            .show();
    }

    /**
     * 提交举报
     */
    private void submitReport(String reason, String description) {
        String token = TokenManager.getToken(this);
        ReportRequest request = new ReportRequest(reason, description);
        
        apiService.reportPost(token, postId, request)
                .enqueue(new Callback<GenericResponse>() {
                    @Override
                    public void onResponse(Call<GenericResponse> call, Response<GenericResponse> response) {
                        if (response.isSuccessful()) {
                            Toast.makeText(PostDetailActivity.this, "举报成功", Toast.LENGTH_SHORT).show();
                            CrashReport.postCatchedException(new Exception("Event: Report Post"));
                        } else {
                            Toast.makeText(PostDetailActivity.this, "举报失败", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<GenericResponse> call, Throwable t) {
                        Toast.makeText(PostDetailActivity.this, "网络连接失败", Toast.LENGTH_SHORT).show();
                    }
                });
    }

    @Override
    public void onCommentLikeClick(int commentId) {
        String token = TokenManager.getToken(this);
        if (token == null || token.isEmpty()) {
            Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show();
            return;
        }

        apiService.toggleLike(token, "comment", commentId)
                .enqueue(new Callback<LikeResponse>() {
                    @Override
                    public void onResponse(Call<LikeResponse> call, Response<LikeResponse> response) {
                        if (response.isSuccessful()) {
                            loadComments(); // 刷新评论列表
                        }
                    }

                    @Override
                    public void onFailure(Call<LikeResponse> call, Throwable t) {
                        Toast.makeText(PostDetailActivity.this, "操作失败", Toast.LENGTH_SHORT).show();
                    }
                });
    }

    @Override
    public void onCommentReplyClick(int commentId, String username) {
        // TODO: 实现回复功能
        Toast.makeText(this, "回复 " + username, Toast.LENGTH_SHORT).show();
    }

    /**
     * 格式化时间
     */
    private String formatTime(String createdAt) {
        // TODO: 实现时间格式化
        return createdAt;
    }

    /**
     * 提取错误信息
     */
    private String extractErrorMessage(Response<?> response) {
        try {
            if (response != null && response.errorBody() != null) {
                String raw = response.errorBody().string();
                if (!TextUtils.isEmpty(raw)) {
                    try {
                        org.json.JSONObject obj = new org.json.JSONObject(raw);
                        if (obj.has("error")) {
                            return obj.optString("error");
                        }
                    } catch (Exception jsonEx) {
                        return raw;
                    }
                }
            }
        } catch (Exception e) {
            // 忽略
        }
        return null;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        binding = null;
    }

    @Override
    protected String getPageName() {
        return "帖子详情页";
    }
}

